from django.http import HttpResponse
from django.utils.timezone import make_aware
from django.db.models import Sum

from ...models.powerlogs import PowerLogs

from ...utils.data_handle import chatpowerlogs_handler
from ...utils.users import get_login_user_id

from datetime import datetime, timedelta
import json


def powerlog_list(request):
    '''
    获取用户算力日志
    POST
    {
        "model": "qwen-plus",
        "date": [
            "2024-08-20",
            "2024-08-23"
        ],
        "page": 1,
        "page_size": 20
    }
    '''
    if request.method == 'POST':
        json_b = request.body
        json_str = json_b.decode('utf-8')
        json_obj = json.loads(json_str)


        search_dict = dict()
        # 获取用户id
        userid = get_login_user_id(request, isadmin=False)
        search_dict['user_id'] = userid

        if "model" in json_obj and json_obj['model']:
            search_dict["model"] = json_obj['model']

        if json_obj['date'] and len(json_obj['date']) == 2:
            start_date = make_aware(datetime.strptime(json_obj['date'][0], "%Y-%m-%d"))
            end_date = make_aware(datetime.strptime(json_obj['date'][1], "%Y-%m-%d")) + timedelta(days=1)

            search_dict["created_at__gte"] = start_date
            search_dict["created_at__lte"] = end_date

        all_chatpowerlogs = PowerLogs.objects.filter(**search_dict).order_by('-id')
        all_chatpowerlogs_data = chatpowerlogs_handler(all_chatpowerlogs, json_obj['page'], json_obj['page_size'])

        res_mes = {
            "code": 0,
            "data": all_chatpowerlogs_data
        }
        res_mes_json = json.dumps(res_mes, ensure_ascii=False)
        return HttpResponse(res_mes_json)

